package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Clazz struct {
	Id       int        `orm:"column(id);pk;auto"` //主键
	Name     string     `orm:"size(50)"`           //名称
	Students []*Student `orm:"reverse(many)"`
	//Teachers []Teacher
	//Courses []Course
	//Students []Student
}

func init() {
	orm.RegisterModel(new(Clazz))
}
func (m *Clazz) TableName() string {
	return "clazz"
}

/**
统计
*/
func CountClazzAll(ormObj orm.Ormer) int64 {
	count, _ := ormObj.QueryTable(&Clazz{}).Count()
	return count
}

/**
添加
*/
func SaveClazz(ormObj orm.Ormer, clazz Clazz) {
	ormObj.Insert(clazz)
}

/**
修改
*/
func UpdateClazz(ormObj orm.Ormer, clazz Clazz) {
	ormObj.Update(clazz)
}

/**
删除
*/
func DeleteClazz(ormObj orm.Ormer, clazz Clazz) {
	ormObj.Delete(clazz)
}

/**
获取分页班级信息
*/
func FindClazzByPage(ormObj orm.Ormer, pos int, rows int) (*[]Clazz, error) {
	classes := new([]Clazz)
	if _, err := ormObj.QueryTable(&Clazz{}).Limit(rows).Offset(pos).All(classes); err != nil {
		fmt.Println(err)
		return nil, err
	}
	for i := 0; i < len(*classes); i++ {
		ormObj.LoadRelated(&(*classes)[i], "Students")
	}
	//for index, val := range *classes {
	//	ormObj.LoadRelated(&val,"Students")
	//	fmt.Printf("%d %d",index,len(val.Students))
	//}

	fmt.Println(len(*classes))
	return classes, nil
}

/**
获取所有班级信息
*/
func FindClazzAll(ormObj orm.Ormer) (*[]Clazz, error) {
	classes := new([]Clazz)
	if _, err := ormObj.QueryTable(&Clazz{}).All(classes); err != nil {
		fmt.Println(err)
		return nil, err
	}
	//for i:=0; i<len(*classes) ;i++  {
	//	ormObj.LoadRelated(&(*classes)[i],"Students")
	//}
	//for index, val := range *classes {
	//	ormObj.LoadRelated(&val,"Students")
	//	fmt.Printf("%d %d",index,len(val.Students))
	//}

	fmt.Println(len(*classes))
	return classes, nil
}

/**
通过ID获取Clazz对象
*/
func GetClazzById(ormObj orm.Ormer, id int) (v *Clazz, err error) {
	fmt.Printf("id = %d \n", id)
	v = &Clazz{Id: id}
	if err = ormObj.QueryTable(&Clazz{}).Filter("Id", id).RelatedSel().One(v); err == nil {
		// 获取关系字段，ormObj.LoadRelated(v, "Roles") 这是关键
		// 查找该用户所属的角色
		if _, err = ormObj.LoadRelated(v, "Students"); err != nil {
			fmt.Print(err)
			return nil, err
		}
		//fmt.Printf("id2 = %d \n",id)
		return v, nil
	}
	return nil, err
}
